<template>
  <div class="coupon auditCmpt">
    <!-- {{carrier}} -->
    <!-- 查询表单 -->
    <div v-if="!isDetail">
      <div class="form-baseinfo">
        <LPSearchBar
          v-model="searchModel"
          :search-data="searchData"
          label-width="100px"
          @handleSearchSubmit="handleSearchSubmit"
          @handleSearchReset="handleSearchReset"
        />
        <!-- 表格列表 -->
        <div class="btn_area">
          <el-button size="medium" type="primary" @click="insert">新增</el-button>
          <el-button size="medium" type="primary" @click="exportCouponDailog = true">导入优惠券</el-button>
        </div>
      </div>
      <div class="form-baseinfo">
        <LPTablePage
          :show-index="true"
          index-label="序号"
          :show-indexfixed="false"
          :table-data="tableData"
          :table-column="tableColumn"
          :total="total"
          :current-page="currentPage"
          align="center"
          @handleSizeChange="handleSizeChange"
          @handleCurrentChange="handleCurrentChange"
        >
          <template slot="rate" slot-scope="{ row }">
            <div>{{ row.rate == 1 ? '周期性发放' : '单次发放' }}</div>
          </template>
          <template slot="enabledMark" slot-scope="{ row }">
            <div>{{ row.enabledMark == 1 ? '启用' : '禁用' }}</div>
          </template>
          <template slot="recordMaterials" slot-scope="{ row }">
            <el-link type="primary" @click="couponDetail(row.couponMaterials)">查看详情</el-link>
          </template>
          <template slot="cz" slot-scope="{ row }">
            <el-button type="text" @click="handleDetail(row)">详情</el-button>
            <el-button type="text" @click="handleEdit(row)">编辑</el-button>
            <el-button
              v-if="row.enabledMark == 1"
              style="color: #f56c6c"
              type="text"
              @click="handleDoEnabled(row, '禁用')"
              >禁用</el-button
            >
            <el-button v-else type="text" @click="handleDoEnabled(row, '启用')">启用</el-button>
            <el-button style="color: #f56c6c" type="text" @click="handleDelete(row)">删除</el-button>
          </template>
        </LPTablePage>
      </div>
    </div>
    <div v-else class="form-baseinfo">
      <coupon-detail :back-data="backData" :go-to-url="goToUrl" :coupon-id="couponId" @detailClose="detailClose" />
    </div>
    <el-dialog
      class="newAdd"
      :title="dialogTitle"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="dialogClose"
      :visible.sync="insertDailog"
      width="1080px"
      style="margin-top: -100px"
    >
      <el-form v-if="!insertProduct" ref="insertForm" :rules="rules" class="formStyle" :model="insertModel">
        <div class="couponInfo">
          <el-form-item label="优惠券名称" prop="name">
            <el-input v-model="insertModel.name" />
          </el-form-item>
          <el-form-item label="部门" prop="">
            <el-select v-model="insertModel.departmentIds" filterable multiple @change="departmentIdsChange">
              <el-option
                v-for="item in findList"
                :key="item.orgId"
                :value="item.orgId"
                :label="item.orgName + '( ' + item.orgId + ' )'"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="岗位" prop="">
            <el-select v-model="insertModel.postIds" filterable multiple @change="postIdsChange">
              <el-option
                v-for="(item, index) in jobList"
                :key="index"
                :value="item.key"
                :label="item.value + '( ' + item.key + ' )'"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="insertModel.postIds.length > 0" label="人员：" prop="">
            <el-select v-model="insertModel.userIds" filterable multiple style="width: 280px" @change="userIdsChange">
              <el-option v-for="(item, index) in userList" :key="index" :value="item.key" :label="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item v-else label="人员录入" prop="">
            <el-input v-model="insertModel.userNameLists" style="width: 280px" />
          </el-form-item>
        </div>

        <div class="frequency">
          <el-form-item label="发放频率：" prop="">
            <div class="radio">
              <el-radio v-model="insertModel.rate" class="periodRadio" :label="1">仅触发后一次</el-radio>
              <el-radio v-model="insertModel.rate" class="onceRadio" :label="2">单次发放</el-radio>
            </div>
            <div v-if="insertModel.rate == 1" class="option">
              <span>每</span>
              <el-input-number
                v-model="insertModel.per"
                style="width: 50px; margin-left: 7px"
                :controls="false"
                :precision="0"
              />
              <!-- <el-input style="width: 50px;margin-left: 7px;" v-model="insertModel.per"></el-input> -->
              <el-select v-model="insertModel.cycle" style="width: 100px; margin-left: 7px">
                <el-option v-for="item in E_CouponCycle" :key="item.id" :value="item.value" :label="item.label" />
              </el-select>
              <span style="margin-left: 7px">起始计算时间</span>
              <el-date-picker
                v-model="insertModel.startTime"
                :picker-options="pickerOptions"
                type="datetime"
                style="width: 220px; margin-left: 7px"
                placeholder="选择日期"
              />
              <span style="margin-left: 7px">有效期限即发放周期，凌晨发放</span>
            </div>
          </el-form-item>
          <el-form-item label="" prop="">
            <div v-if="insertModel.rate == 2" class="option">
              <span>发放时间</span>
              <el-date-picker
                v-model="insertModel.provideTime"
                type="datetime"
                style="width: 220px; margin-left: 7px"
                placeholder="选择日期"
              />
              <span style="margin-left: 7px">有效期</span>
              <el-date-picker
                v-model="insertModel.startTime"
                type="datetime"
                style="width: 220px; margin-left: 7px"
                placeholder="选择日期"
              />
              <span style="margin-left: 7px">至</span>
              <el-date-picker
                v-model="insertModel.endTime"
                default-time="23:59:59"
                type="datetime"
                style="width: 220px; margin-left: 7px"
                placeholder="选择日期"
              />
            </div>
          </el-form-item>
        </div>

        <div class="stat">
          <el-form-item label="状态：" prop="">
            <el-radio v-model="insertModel.enabledMark" :label="1">启用</el-radio>
            <el-radio v-model="insertModel.enabledMark" :label="0">禁用</el-radio>
          </el-form-item>
        </div>

        <div class="materialInfo">
          <el-form-item label="" prop="">
            <div class="text">物料信息</div>
            <el-button class="button" type="primary" size="medium" @click="insertFunction">添加</el-button>
            <el-button class="button" type="primary" @click="exportInfo">下载模板</el-button>
            <el-button class="button" size="small" @click="exportInfoDailog = true">导入</el-button>
          </el-form-item>
        </div>
        <el-form-item label="" style="height: 200px">
          <LPTablePage
            :show-index="true"
            :show-indexfixed="false"
            index-label="序号"
            :show-page="false"
            :table-data="insertData"
            :table-column="insertColumn"
            max-height="250"
            :total="total"
            :current-page="currentPage"
            align="center"
          >
            <template slot="smallCategoryNo" slot-scope="{ row }">
              <div v-if="row.level >= 3">{{ row.smallCategoryNo }}</div>
              <div v-else />
            </template>
            <template slot="smallCName" slot-scope="{ row }">
              <div v-if="row.level >= 3">{{ row.smallCName }}</div>
              <div v-else />
            </template>
            <template slot="materialCode" slot-scope="{ row }">
              <div v-if="row.level == 4">{{ row.materialCode }}</div>
              <div v-else />
            </template>
            <template slot="materialName" slot-scope="{ row }">
              <div v-if="row.level == 4">{{ row.materialName }}</div>
              <div v-else />
            </template>
            <template slot="count" slot-scope="{ row }">
              <el-input-number v-model="row.count" size="mini" style="width: 95%" :controls="false" :precision="0" />
            </template>
            <template slot="handler" slot-scope="scope">
              <el-button style="color: red" type="text" @click="deleteInfo(scope.$index, scope)">删除</el-button>
            </template>
          </LPTablePage>
        </el-form-item>
      </el-form>
      <el-form
        v-else
        ref="insertProduct"
        style="margin-top: -10px"
        class="formStyle"
        label-width="80px"
        :model="insertProductModel"
      >
        <el-row>
          <el-col :span="6.5">
            <el-form-item label="物料中类" prop="">
              <el-select
                v-model="insertProductModel.centreTypeId"
                style="width: 95%"
                clearable
                @change="centreTypeChange"
              >
                <el-option v-for="item in centreType" :key="item.id" :label="item.cName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6.5">
            <el-form-item label="物料小类" prop="">
              <el-select
                v-model="insertProductModel.smallTypeId"
                style="width: 95%"
                clearable
                @change="smallTypeChange"
              >
                <el-option v-for="item in smallType" :key="item.categoryNo" :label="item.cName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6.5">
            <el-form-item label="物料名称" prop="">
              <el-input v-model="insertProductModel.productName" style="width: 95%" />
            </el-form-item>
          </el-col>
          <el-col :span="4.5">
            <div style="padding-left: 40px">
              <el-button type="primary" size="medium" @click="selectApiList">查询</el-button>
              <el-button size="medium" @click="insertProductModelResetting">重置</el-button>
            </div>
          </el-col>
        </el-row>
        <el-form-item label="物料维度" prop="">
          <el-radio-group v-model="insertProductModel.level" @change="levelChange">
            <!-- <el-radio :label="2">物料中类</el-radio> -->
            <el-radio :label="3">物料小类</el-radio>
            <el-radio :label="4">物料名称</el-radio>
          </el-radio-group>
        </el-form-item>

        <LPTablePage
          ref="insertProductTable"
          selection
          :show-page="false"
          :show-index="true"
          index-label="序号"
          :show-indexfixed="false"
          :table-data="insertProductData"
          :table-column="insertProductColumn"
          max-height="550"
          :total="total"
          :current-page="currentPage"
          align="center"
          @handleSelectionChange="handleSelectionChange"
        >
          <template slot="smallCategoryNo" slot-scope="{ row }">
            <div v-if="insertProductModel.level >= 3">{{ row.smallCategoryNo }}</div>
            <div v-else>-</div>
          </template>
          <template slot="smallCName" slot-scope="{ row }">
            <div v-if="insertProductModel.level >= 3">{{ row.smallCName }}</div>
            <div v-else>-</div>
          </template>
          <template slot="materialCode" slot-scope="{ row }">
            <div v-if="insertProductModel.level == 4">{{ row.materialCode }}</div>
            <div v-else>-</div>
          </template>
          <template slot="materialName" slot-scope="{ row }">
            <div v-if="insertProductModel.level == 4">{{ row.materialName }}</div>
            <div v-else>-</div>
          </template>
        </LPTablePage>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="insertCancel">取 消</el-button>
        <el-button type="primary" size="medium" @click="insertSave">保存</el-button>
      </span>
    </el-dialog>
    <el-dialog
      class=""
      :title="dialogTitle"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="dialogClose1"
      :visible.sync="couponDialog"
      width="1080px"
      style="margin-top: -100px"
    >
      <LPTablePage
        :show-page="false"
        :show-index="true"
        index-label="序号"
        :show-indexfixed="false"
        :table-data="couponDetailTable"
        :table-column="couponDetailTableColumn"
        max-height="550"
        align="center"
      >
        <template slot="smallCategoryNo" slot-scope="{ row }">
          <div v-if="row.level >= 3">{{ row.smallCategoryNo }}</div>
          <div v-else />
        </template>
        <template slot="smallCName" slot-scope="{ row }">
          <div v-if="row.level >= 3">{{ row.smallCName }}</div>
          <div v-else />
        </template>
        <template slot="materialCode" slot-scope="{ row }">
          <div v-if="row.level == 4">{{ row.materialCode }}</div>
          <div v-else />
        </template>
        <template slot="materialName" slot-scope="{ row }">
          <div v-if="row.level == 4">{{ row.materialName }}</div>
          <div v-else />
        </template>
      </LPTablePage>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="dialogClose1">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog
      class=""
      title="导入模板"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="exportInfoDailog"
      width="400px"
    >
      <el-upload
        ref="upload"
        class="upload-demo"
        drag
        :action="public_config.file_api + `/api/file-management/files/upload`"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :show-file-list="true"
        :headers="headers"
        :limit="1"
        :on-exceed="handleExceed"
        :before-remove="beforeRemove"
        :on-success="handleSuccess"
        :file-list="fileList"
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="uploadCancel">取 消</el-button>
        <el-button type="primary" size="medium" @click="uploadSave">保存</el-button>
      </span>
    </el-dialog>
    <el-dialog
      class=""
      style="margin-top: -40px"
      title="导入优惠券"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="exportCouponDailog"
      :width="exportCouponWidth"
      :before-close="uploadCouponCancel"
    >
      <div v-if="!exportCouponResult">
        <el-upload
          ref="upload"
          class="upload-demo"
          drag
          :action="public_config.file_api + `/api/file-management/files/upload`"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :show-file-list="true"
          :headers="headers"
          :limit="1"
          :on-exceed="handleExceed"
          :before-remove="beforeRemove"
          :on-success="handleSuccess"
          :file-list="fileList"
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
        <el-button type="text" @click="exportCouponInfo">下载导入模板</el-button>
        <div style="color: crimson; font-size: 12px">
          导入要求:
          <div style="margin-top: 8px">1、优惠券名称不可以重复</div>
          <div style="margin-top: 4px">
            2、员工工号和工号之间，用英文逗号隔开，最后一个工号后不要标点，如：BX2601931,BX2601932
          </div>
          <div style="margin-top: 4px">
            3、起始计算时间：格式要求yyyy-mm-dd，文本格式，切勿用日期格式。如：2024-01-22
            注：录入的“起始计算时间”是实际发放优惠券日期的后一天，例如：需要在9.1号发放优惠券，则该处“起始计算时间”需录入9.2号。请务必注意。且发放优惠券时间必须是未来的时间，若是当前时间或已过去的时间，该优惠券将无法发放。
          </div>
          <div style="margin-top: 4px">
            4、物料信息：编码即物料编码，如果是物料小类，则用物料小类编号，编码和数量之间用英文-隔开，“编码-数量”两两之间用英文逗号隔开。
          </div>
        </div>
      </div>
      <div v-else>
        <LPTablePage
          :show-index="true"
          index-label="序号"
          :show-indexfixed="false"
          :table-data="exportResultData"
          :show-page="false"
          :table-column="exportResultTableCoulmn"
          align="center"
        >
          <template slot="message" slot-scope="{ row }">
            <span style="color: #f56c6c">{{ row.message }}</span>
          </template>
        </LPTablePage>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="uploadCouponCancel">取 消</el-button>
        <el-button v-if="exportCouponResult" size="medium" @click="uploadCouponAgain">重新导入</el-button>
        <el-button v-if="!exportCouponResult" type="primary" size="medium" @click="uploadCouponSave">导入</el-button>
        <el-button v-else type="primary" size="medium" @click="exportCouponSave">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { download, parseTime } from '@/utils/lpUtils'
import { getProductList } from '@/api/LaborProtection/product'
import { doEnabledCoupon } from '@/api/LaborProtection/couponRecord'
import { getCategoryInfo } from '@/api/LaborProtection/categoryInfo'
import { getCategoryInfoList } from '@/api/LaborProtection/categoryInfo'
import { getFindList, getUserList, getJobList } from '@/api/LaborProtection/employee'
import {
  insertCouponList,
  updateCouponList,
  getCouponList,
  deleteCouponList,
  getByIdCouponList,
  GetCouponListExcel,
  GetCouponExcel,
  importCoupon,
  importCouponList,
  queryMaterial,
  importCouponSave
} from '@/api/LaborProtection/counpon'
import couponDetail from './detail.vue'
import LPTablePage from '@/components/LPTablePage/index.vue'
import LPSearchBar from '@/components/LPSearchBar/index.vue'

export default {
  name: 'Coupon',
  components: {
    couponDetail,
    LPSearchBar,
    LPTablePage
  },
  data() {
    return {
      searchModel: {},
      searchData: [
        { label: '', placeholder: '优惠券名称', prop: 'name' },
        { label: '', placeholder: '员工工号', prop: 'userId' },
        { label: '', placeholder: '部门', prop: 'departmentName' },
        { label: '', placeholder: '岗位', prop: 'postName' },
        {
          label: '',
          placeholder: '状态',
          prop: 'enabledMark',
          type: 'select',
          option: [
            { value: -1, label: '全部' },
            { value: 1, label: '启用' },
            { value: 0, label: '禁用' }
          ]
        },
        // { label: '物料名称', placeholder: '请输入', prop: 'userNames' },
        {
          label: '',
          placeholder: '周期',
          prop: 'rate',
          type: 'select',
          option: [
            {
              label: '周期性发放',
              value: 1
            },
            {
              label: '单次发放',
              value: 2
            }
          ]
        },
        { label: '', prop: 'StartOrderTime', type: 'datetimerange', placeholder: '开始时间', width: '100px' }
      ],
      exportCouponDailog: false,
      exportCouponResult: false,
      exportResultData: [],
      exportResultTableCoulmn: [
        { label: '优惠券名称', prop: 'couponName' },
        { label: '员工(工号,工号)', prop: 'userName' },
        { label: '发放频率(1周期,2单次)', prop: 'rateName' },
        { label: '发放周期(1年,2月)', prop: 'cycleName' },
        { label: '周期数', prop: 'per' },
        { label: '起始计算时间', prop: 'startTime' },
        { label: '物料信息(编号-数量)', prop: 'couponMaterials' },
        { label: '错误信息', prop: 'message', render: true }
      ],
      // 列表数据
      tableData: [],
      // 表格字段
      tableColumn: [
        { label: '优惠券名称', prop: 'name' },
        { label: '部门', prop: 'departmentNames' },
        { label: '岗位', prop: 'postNames' },
        { label: '员工工号', prop: 'userIds' },
        { label: '发放频率', prop: 'rate', render: true },
        { label: '物料名称', prop: 'recordMaterials', render: true },
        { label: '状态', prop: 'enabledMark', render: true },
        { label: '创建人', prop: 'createUserName' },
        { label: '创建时间', prop: 'createDate' },
        { label: '操作', prop: 'cz', render: true, width: 220 }
      ],
      rules: {
        name: [{ required: true, message: '请输入优惠券名称', trigger: 'bulr' }],
        departmentIds: [{ required: true, message: '请选择部门', trigger: 'change' }]
      },

      total: 0,
      currentPage: 1,
      pageSize: 10,
      headers: {
        Authorization: 'bearer ' + getToken()
      },
      insertData: [],
      // 表格字段
      insertColumn: [
        { label: '物料大类', prop: 'largeCName' },
        { label: '中类编码', prop: 'middleCName' },
        { label: '物料中类', prop: 'middleCategoryNo' },
        { label: '小类编码', prop: 'smallCategoryNo', render: true },
        { label: '物料小类', prop: 'smallCName', render: true },
        { label: '数量', prop: 'count', render: true, fixed: 'right' },
        { label: '操作', prop: 'handler', render: true, fixed: 'right' }
      ],
      couponDetailTable: [],
      couponDetailTableColumn: [
        { label: '物料大类', prop: 'largeCName' },
        { label: '中类编码', prop: 'middleCName' },
        { label: '物料中类', prop: 'middleCategoryNo' },
        { label: '小类编码', prop: 'smallCategoryNo', render: true },
        { label: '物料小类', prop: 'smallCName', render: true },
        { label: '物料编码', prop: 'materialCode', render: true },
        { label: '物料名称', prop: 'materialName', render: true },
        { label: '数量', prop: 'count' }
      ],
      insertProductData: [],
      insertProductColumn: [
        { label: '物料大类', prop: 'largeCName', width: 160 },
        { label: '中类编码', prop: 'middleCName' },
        { label: '物料中类', prop: 'middleCategoryNo' },
        { label: '小类编码', prop: 'smallCategoryNo', render: true },
        { label: '物料小类', prop: 'smallCName', render: true },
        { label: '物料编码', prop: 'materialCode', render: true },
        { label: '物料名称', prop: 'materialName', render: true }
      ],
      exportCouponWidth: '400px',
      url: '',
      fileName: '',
      couponId: '',
      dialogTitle: '',
      backData: '',
      fileList: [],
      insertDailog: false,
      insertProduct: false,
      dialogTitle: '优惠券详情',
      couponDialog: false,
      exportInfoDailog: false,
      insertProductModel: {
        productName: '',
        centreTypeId: '',
        centreCategoryNo: '',
        smallTypeId: '',
        smallTypeName: '',
        smallTypeCategoryNo: '',
        level: 4
      },
      pickerOptions: {
        disabledDate: (date) => {
          const currentDate = new Date()
          return date < currentDate
        }
      },
      insertModel: {
        provideTime: '',
        startTime: '',
        endTime: '',
        enabledMark: 1,
        rate: 1,
        userNameLists: '',
        departmentIds: [],
        userIds: [],
        postIds: []
      },
      isDetail: false,
      goToUrl: '',
      id: '',
      types: [],
      jobList: [],
      userList: [],
      findList: [],
      smallType: [],
      centreType: [],
      selectionList: [],
      insertDataList: [],
      E_CouponCycle: [
        {
          label: '月',
          value: 2
        },
        {
          label: '年',
          value: 1
        }
      ]
    }
  },
  mounted() {
    this.initSet(), this.getCategoryInfo(2)
    this.getList()
    // this.getProductList();
    this.getFindList()
  },
  methods: {
    dialogClose1() {
      this.couponDialog = false
      this.couponDetailTable = []
    },
    couponDetail(row) {
      console.log(row)
      this.couponDetailTable = row
      this.couponDialog = true
    },
    initSet() {
      if (typeof this.$route.query.data === 'undefined') return
      const query = JSON.parse(this.$route.query.data)
      this.couponId = query.id
      this.goToUrl = query.back
      this.backData = query.backData
      this.isDetail = true
    },
    handleDoEnabled(row, title) {
      this.$confirm(`是否${title}该条信息?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(() => {
          const data = [row.id]
          doEnabledCoupon(data).then((res) => {
            this.$notify({
              title: '操作',
              message: `${title}成功`,
              type: 'success'
            })
            this.getList()
          })
        })
        .catch(() => {
          this.$notify({
            title: '操作',
            message: `已取消${title}`,
            type: 'info'
          })
        })
    },
    levelChange() {
      this.$nextTick(() => {
        this.$refs.insertProductTable.clearSelection()
      })
      this.getAllProductList()
    },
    handleSelectionChange(allList) {
      this.selectionList = allList
    },
    getAllProductList() {
      const params = {}
      if (this.insertProductModel.centreCategoryNo != '') {
        params.MiddleNo = this.insertProductModel.centreCategoryNo
      }
      if (this.insertProductModel.smallTypeCategoryNo != '') {
        params.SmallNo = this.insertProductModel.smallTypeCategoryNo
      }
      if (this.insertProductModel.productName != '') {
        params.PName = this.insertProductModel.productName
      }
      queryMaterial(params).then((res) => {
        this.$refs.insertProductTable.clearSelection()
        if (this.insertProductModel.level == 2) {
          this.$delete(this.insertProductColumn[6], 'width')
          const map = new Map()
          const qc = res.filter((key) => !map.has(key.middleCategoryNo) && map.set(key.middleCategoryNo, 1))
          this.insertProductData = qc
          if (qc.length == 0) return
          const tempArr = this.insertData.filter((item) => item.level == 2)
          const tempSelectionList = []
          qc.forEach((item) => {
            tempArr.forEach((tempItem) => {
              if (item.middleCategoryNo == tempItem.middleCategoryNo) {
                tempSelectionList.push(item)
              }
            })
          })
          this.$refs.insertProductTable.setSelection(tempSelectionList)
        } else if (this.insertProductModel.level == 3) {
          this.$delete(this.insertProductColumn[6], 'width')
          const map = new Map()
          const qc = res.filter((key) => !map.has(key.smallCategoryNo) && map.set(key.smallCategoryNo, 1))
          this.insertProductData = qc
          if (qc.length == 0) return
          const tempArr = this.insertData.filter((item) => item.level == 3)
          const tempSelectionList = []
          qc.forEach((item) => {
            tempArr.forEach((tempItem) => {
              if (item.smallCategoryNo == tempItem.smallCategoryNo) {
                tempSelectionList.push(item)
              }
            })
          })
          this.$refs.insertProductTable.setSelection(tempSelectionList)
        } else {
          this.insertProductData = res
          if (res == 0) return
          const tempArr = this.insertData.filter((item) => item.level == 4)
          this.insertProductColumn[6].width = 320
          const tempSelectionList = []
          res.forEach((item) => {
            tempArr.forEach((tempItem) => {
              if (item.materialCode == tempItem.materialCode) {
                tempSelectionList.push(item)
              }
            })
          })
          this.$refs.insertProductTable.setSelection(tempSelectionList)
        }
      })
    },
    selectApiList() {
      this.getAllProductList()
      // if(this.insertProductModel.level == 2){
      //   if(this.insertProductModel.centreTypeId == ''){
      //     return this.$message.error('请选择物料中类或者切换物料维度');
      //   }
      // }else if(this.insertProductModel.level == 3){
      //   if(this.insertProductModel.smallTypeId == ''){
      //     return this.$message.error('请选择物料小类或者切换物料维度');
      //   }
      // }
      // else if(this.insertProductModel.level == 4){
      //   if(this.insertProductModel.productName == ''){
      //     return this.$message.error('请选择物料名称或者切换物料维度');
      //   }
      // }
    },
    insertProductModelResetting() {
      this.smallType = []
      this.types = []
      this.insertProductModel.productName = ''
      this.insertProductModel.smallTypeCategoryNo = ''
      this.insertProductModel.centreCategoryNo = ''
      this.insertProductModel.centreTypeId = ''
      this.insertProductModel.smallTypeId = ''
    },
    getProductList(QCategoryNo) {
      const data = {
        QCategoryNo: QCategoryNo,
        SkipCount: 0
      }
      getProductList(data).then((res) => {
        this.types = res.items
      })
    },
    getproductName(qCategoryNo) {
      const params = {
        QCategoryNo: qCategoryNo
      }
      getCategoryInfoList(params).then((res) => {})
    },
    smallTypeChange(v) {
      if (v == '') {
        this.insertProductModel.smallTypeCategoryNo = ''
      }
      this.smallType.forEach((item) => {
        if (item.id == v) {
          this.insertProductModel.smallTypeCategoryNo = item.categoryNo
          this.getproductName(item.categoryNo)
          this.getProductList(item.categoryNo)
        }
      })
    },
    centreTypeChange(v) {
      this.insertProductModel.smallTypeId = ''
      this.insertProductModel.centreCategoryNo = ''
      this.centreType.forEach((item) => {
        if (item.id == v) {
          this.insertProductModel.centreCategoryNo = item.categoryNo
          this.getCategoryInfo(3, item.categoryNo)
        }
      })
    },
    /**
     *  1：大类 2：中类 3：小类
     * @param {*} type
     */
    getCategoryInfo(type, parentId) {
      const data = {
        CCLass: type,
        SkipCount: 0
      }
      if (parentId) {
        data.parentId = parentId
      }
      getCategoryInfo(data).then((res) => {
        if (!res.error) {
          if (type == 1) {
          } else if (type == 2) {
            this.centreType = res.items
          } else {
            this.smallType = res.items
          }
        }
      })
    },
    detailClose() {
      this.goToUrl = ''
      this.couponId = ''
      this.isDetail = false
    },
    handleDetail(row) {
      this.couponId = row.id
      this.isDetail = true
    },
    uploadCouponAgain() {
      this.url = ''
      this.fileName = ''
      this.fileList = []
      this.exportCouponResult = false
      this.exportCouponWidth = '400px'
      this.exportResultData = []
    },
    uploadCouponSave() {
      const data = {
        fileUrl: this.url,
        fileName: this.fileName
      }
      if (this.url == '' || this.fileName == '') {
        return this.$message.error('导入文件不能为空')
      }
      importCouponList(data).then((res) => {
        this.exportResultData = res
        this.exportCouponWidth = '1080px'
        this.exportCouponResult = true
      })
    },
    exportCouponSave() {
      const data = [...this.exportResultData]
      importCouponSave(data).then((res) => {
        this.$message.success('导入成功')
        this.uploadCouponCancel()
        this.getList()
      })
    },
    uploadSave() {
      const data = {
        fileUrl: this.url,
        fileName: this.fileName
      }
      if (this.url == '' || this.fileName == '') {
        return this.$message.error('导入文件不能为空')
      }
      importCoupon(data).then((res) => {
        this.insertData = res
        this.exportInfoDailog = false
        this.handleRemove()
        this.beforeRemove()
        this.$message.success('导入成功')
      })
    },
    uploadCancel() {
      this.url = ''
      this.fileName = ''
      this.$refs.upload.clearFiles()
      this.exportInfoDailog = false
    },
    uploadCouponCancel() {
      this.url = ''
      this.fileName = ''
      this.fileList = []
      this.exportCouponResult = false
      this.exportCouponWidth = '400px'
      this.exportCouponDailog = false
    },
    handleRemove(file, fileList) {
      this.fileList = []
      this.fileName = ''
      this.url = ''
    },
    handlePreview(file) {},
    handleExceed() {
      this.$message.warning(`限制选择 1 个文件`)
    },
    beforeRemove(file, fileList) {
      // return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleSuccess(res, file) {
      this.url = public_config.file_api + '/api/file-management/files/www/' + file.response
      this.fileName = file.name
    },
    handleEdit(row) {
      getByIdCouponList(row.id).then((res) => {
        this.id = res.id
        res.userNameLists = ''
        console.log(res)
        this.insertModel = JSON.parse(JSON.stringify(res))
        let departmentIds = []
        if (res.departmentIds != '') {
          departmentIds = res.departmentIds.split(',')
          this.insertModel.departmentIds = departmentIds
          this.departmentIdsChange(departmentIds)
        }
        let postIds = []
        if (res.postIds != '') {
          postIds = res.postIds.split(',')
          this.insertModel.postIds = postIds
          this.postIdsChange(postIds)
          if (res.userIds != '') {
            this.insertModel.userIds = res.userIds.split(',')
          }
        } else {
          this.insertModel.userNameLists = res.userIds
        }

        this.insertData = res.couponMaterials

        this.$nextTick(() => {
          this.dialogTitle = '修改'
          this.insertDailog = true
        })
      })
    },
    // getProductList() {
    //   let data = {};
    //   getProductList(data).then(res => {
    //     this.insertDataList = res.items;
    //   })
    // },
    insert() {
      this.dialogTitle = '新增'
      this.insertDailog = true
    },
    insertFunction() {
      this.insertProduct = true
      this.getAllProductList()
    },
    materialCodeChange(index) {
      this.insertDataList.forEach((item) => {
        if (item.pNo == this.insertData[index].materialCode) {
          this.insertData[index].materialName = item.pTitle
          this.insertData[index].materialId = item.id
        }
      })
    },
    exportInfo() {
      const params = {}
      GetCouponListExcel(params).then((res) => {
        console.log(res)
        download(res, '优惠劵物料模版')
      })
    },
    exportCouponInfo() {
      const params = {}
      GetCouponExcel(params).then((res) => {
        console.log(res)
        download(res, '优惠劵模版')
      })
    },
    deleteInfo(index, scope) {
      console.log(scope)
      this.$confirm('是否删除该条产品信息', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        closeOnClickModal: false
      })
        .then(({ value }) => {
          this.$message.success('删除成功')
          this.insertData.splice(index, 1)
        })
        .catch(() => {})
    },
    departmentIdsChange(value) {
      if (value == '') {
      }
      this.postIds = []
      const data = {
        departmentIds: value
      }
      getJobList(data).then((res) => {
        this.jobList = res
      })
    },
    userIdsChange(value) {
      if (value == '') {
        this.insertModel.userNames = ''
      }
    },
    postIdsChange(value) {
      if (value == '') {
        this.insertModel.postNames = ''
      }
      this.userIds = []
      const data = {
        departmentJobIds: value
      }
      getUserList(data).then((res) => {
        this.userList = res
      })
    },
    getFindList() {
      const data = {}
      getFindList(data).then((res) => {
        this.findList = res
      })
    },
    // 查询按钮
    handleSearchSubmit() {
      this.currentPage = 1
      this.getList()
    },
    // 重置按钮
    handleSearchReset() {
      this.handleSearchSubmit()
    },
    handleSizeChange(v) {
      this.pageSize = v
      this.currentPage = 1
      this.getList()
    },
    handleCurrentChange(v) {
      this.currentPage = v
      this.getList()
    },
    // exportInfo() {
    //   let params = {
    //     ...this.searchModel,
    //   };
    //   if (typeof this.searchModel.StartOrderTime != "undefined") {
    //     params.SDateTime = parseTime(this.searchModel.StartOrderTime[0]);
    //     params.EDateTime = parseTime(this.searchModel.StartOrderTime[1]);
    //     this.$delete(params, 'StartOrderTime');
    //   }
    //   GetEmployeeConsumeStatisticsExcel(params).then(res => {
    //     console.log(res);
    //     download(res, '员工消费统计')
    //   })
    // },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(() => {
          const data = [row]
          deleteCouponList(data).then((res) => {
            this.$notify({
              title: '操作',
              message: '删除成功',
              type: 'success'
            })
            this.getList()
          })
        })
        .catch(() => {
          this.$notify({
            title: '操作',
            message: '已取消删除',
            type: 'info'
          })
        })
    },
    getList() {
      const params = {
        ...this.searchModel,
        SkipCount: this.currentPage,
        MaxResultCount: this.pageSize
      }
      if (typeof this.searchModel.StartOrderTime !== 'undefined') {
        params.beginCreateTime = parseTime(this.searchModel.StartOrderTime[0])
        params.endCreateTime = parseTime(this.searchModel.StartOrderTime[1])
        this.$delete(params, 'StartOrderTime')
      }
      if (this.searchModel.enabledMark == -1) {
        this.$delete(params, 'enabledMark')
      }
      getCouponList(params).then((res) => {
        if (!res.error) {
          this.tableData = res.items
          this.total = res.totalCount
        }
      })
    },
    dialogClose() {
      this.insertProduct = false
      this.insertDailog = false
      this.id = ''
      this.insertModel = this.$options.data().insertModel
      this.insertData = []
    },
    insertCancel() {
      if (!this.insertProduct) {
        this.dialogClose()
      } else {
        this.insertProductModel = {
          productName: '',
          centreTypeId: '',
          centreCategoryNo: '',
          smallTypeId: '',
          smallTypeName: '',
          smallTypeCategoryNo: '',
          level: 4
        }
        this.insertProduct = false
      }
    },
    insertSave() {
      if (!this.insertProduct) {
        this.$refs.insertForm.validate((validate) => {
          if (!validate) return false
          const data = {
            ...this.insertModel
          }
          data.departmentIds = ''
          data.postIds = ''
          data.userIds = ''
          if (this.insertModel.endTime != '') {
            data.endTime = parseTime(this.insertModel.endTime)
          }
          if (this.insertModel.provideTime != '') {
            data.provideTime = parseTime(this.insertModel.provideTime)
          }
          if (this.insertModel.startTime != '') {
            data.startTime = parseTime(this.insertModel.startTime)
          }
          if (this.insertModel.departmentIds.length > 0) {
            this.insertModel.departmentIds.forEach((item, index) => {
              if (index == 0) {
                this.findList.forEach((findItem) => {
                  if (findItem.orgId == item) {
                    data.departmentNames = findItem.orgName
                  }
                })
                data.departmentIds = item
              } else {
                this.findList.forEach((findItem) => {
                  if (findItem.orgId == item) {
                    data.departmentNames = data.departmentNames + ',' + findItem.orgName
                  }
                })
                data.departmentIds = data.departmentIds + ',' + item
              }
            })
          } else {
            data.departmentNames = ''
          }
          if (this.insertModel.postIds.length > 0) {
            this.insertModel.postIds.forEach((item, index) => {
              if (index == 0) {
                this.jobList.forEach((jobItem) => {
                  if (jobItem.key == item) {
                    data.postNames = jobItem.value
                  }
                })
                data.postIds = item
              } else {
                this.jobList.forEach((jobItem) => {
                  if (jobItem.key == item) {
                    data.postNames = data.postNames + ',' + jobItem.value
                  }
                })
                data.postIds = data.postIds + ',' + item
              }
            })
            if (this.insertModel.userIds.length > 0) {
              this.insertModel.userIds.forEach((item, index) => {
                if (index == 0) {
                  this.userList.forEach((userItem) => {
                    if (userItem.key == item) {
                      data.userNames = userItem.value
                    }
                  })
                  data.userIds = item
                } else {
                  this.userList.forEach((userItem) => {
                    if (userItem.key == item) {
                      data.userNames = data.userNames + ',' + userItem.value
                    }
                  })
                  data.userIds = data.userIds + ',' + item
                }
              })
            }
          } else {
            data.postNames = ''
            data.userIds = this.insertModel.userNameLists
            data.userNames = ''
          }
          this.insertData.forEach((item, index) => {
            item.sort = index
          })
          data.couponMaterials = this.insertData

          if (this.id == '') {
            insertCouponList(data).then((res) => {
              this.$notify({
                title: '操作',
                message: '添加成功',
                type: 'success'
              })
              this.insertCancel()
              this.getList()
            })
          } else {
            data.id = this.id
            updateCouponList(data).then((res) => {
              this.$notify({
                title: '操作',
                message: '修改成功',
                type: 'success'
              })
              this.insertCancel()
              this.getList()
            })
          }
        })
      } else {
        this.selectionList.forEach((item) => {
          item.level = this.insertProductModel.level
        })
        if (this.insertData.length == 0) {
          this.insertData = this.selectionList
        } else {
          this.handleInsertProduct(this.insertProductModel.level)
        }

        this.insertCancel()
      }
    },
    handleInsertProduct(levelFlag) {
      console.log(levelFlag)
      const tempArr = this.insertData.filter((item) => item.level == levelFlag)
      console.log(tempArr)
      if (tempArr.length == 0) {
        this.selectionList.forEach((tempItem) => {
          this.insertData.push(tempItem)
        })
      } else {
        let uniqueObjects = []
        if (levelFlag == 2) {
          uniqueObjects = this.selectionList.filter(
            (obj) => !tempArr.some((obj1) => obj.middleCategoryNo == obj1.middleCategoryNo)
          )
        } else if (levelFlag == 3) {
          uniqueObjects = this.selectionList.filter(
            (obj) => !tempArr.some((obj1) => obj.smallCategoryNo == obj1.smallCategoryNo)
          )
        } else {
          uniqueObjects = this.selectionList.filter(
            (obj) => !tempArr.some((obj1) => obj.materialCode == obj1.materialCode)
          )
        }
        this.insertData.push(...uniqueObjects)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.auditCmpt {
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
  .form-baseinfo:first-child {
    margin: 20px, 0, 20px, -10px;
    border-radius: 3px;
  }
  .btn_area {
    padding: 0.2rem;
    border-top-left-radius: 3px;
    border-top-right-radius: 3px;
    background-color: #fff;
  }
}
::v-deep .search-bar input.el-input__inner {
  width: 1.6rem;
}
.newAdd {
  margin: 0 20px;
  .couponInfo {
    // margin: 0 20px;
    ::v-deep .el-form-item__label {
      text-align: left;
    }
    ::v-deep .el-input__inner {
      width: 430px;
    }
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    align-items: center;
    .el-form-item {
      display: flex;
      flex-direction: column;
      width: 40%;
      height: 70px;
    }
  }
  .frequency {
    margin-top: 10px;
    margin-left: 52px;
    .el-form-item {
      margin-bottom: 0;
    }

    .option {
      margin-left: 80px;
    }
  }
  .stat {
    margin: 30px 0;
    margin-left: 52px;
  }
  .materialInfo {
    margin: 0 52px;
    .text {
      margin-bottom: 10px;
      color: #333333;
      font-size: 18px;
      font-weight: 700;
    }
    .button {
      width: 100px;
      margin: 0 10px;
    }
  }
}
.upload-demo {
  text-align: center;
}
</style>
